package designMode;


import java.util.*;

/**
 * Created by rzd on 2017/4/25.
 */
public class EventDriven {
    public static void main(String[] args) {
        EventSourceObject object = new EventSourceObject();
        //注册监听器
        object.addCusListener(new CusEventListener(){
            @Override
            public void fireCusEvent(CusEvent e) {
                super.fireCusEvent(e);
            }
        });
        //触发事件
        object.setName("eric");
    }
}
class CusEvent extends EventObject {
    private static final long serialVersionUID = 1L;
    private Object source;//事件源

    public CusEvent(Object source){
        super(source);
        this.source = source;
    }

    public Object getSource() {
        return source;
    }

    public void setSource(Object source) {
        this.source = source;
    }
}

class CusEventListener implements EventListener {

    //事件发生后的回调方法
    public void fireCusEvent(CusEvent e){
        EventSourceObject eObject = (EventSourceObject)e.getSource();
        System.out.println("My name has been changed!");
        System.out.println("I got a new name,named \""+eObject.getName()+"\"");    }
}

class EventSourceObject {
    private String name;
    //监听器容器
    private Set<CusEventListener> listener;
    public EventSourceObject(){
        this.listener = new HashSet<CusEventListener>();
        this.name = "defaultname";
    }
    //给事件源注册监听器
    public void addCusListener(CusEventListener cel){
        this.listener.add(cel);
    }
    //当事件发生时,通知注册在该事件源上的所有监听器做出相应的反应（调用回调方法）
    protected void notifies(){
        CusEventListener cel = null;
        Iterator<CusEventListener> iterator = this.listener.iterator();
        while(iterator.hasNext()){
            cel = iterator.next();
            cel.fireCusEvent(new CusEvent(this));
        }
    }
    public String getName() {
        return name;
    }
    //模拟事件触发器，当成员变量name的值发生变化时，触发事件。
    public void setName(String name) {
        if(!this.name.equals(name)){
            this.name = name;
            notifies();
        }
    }
}